<?php
/**
 * YMemory.php
 *
 * @author Hua Yang <htmlcook@gmail.com>
 * @since 2.0
 */

Yii::import('common.components.queue.YQueueInterface');

/**
 * Class YMemory
 */
class YMemory implements YQueueInterface
{
	/**
	 * @var array 队列数组
	 */
	protected $queue;

	/**
	 * @var integer 计数
	 */
	protected $idSequence;

	public function __construct($name)
	{
		$this->queue = array();
		$this->idSequence = 0;
	}

	/**
	 * @param $data
	 * @return mixed
	 */
	public function createItem($data)
	{
		$item = new stdClass();
		$item->item_id = $this->idSequence;
		$item->data = $data;
		$item->created = time();
		$item->expire = 0;
		$this->queue[$item->item_id] = $item;
		return $item->item_id;
	}

	/**
	 * @return integer
	 */
	public function numberOfItems()
	{
		return count($this->queue);
	}

	/**
	 * @param int $leaseTime
	 * @return mixed
	 */
	public function claimItem($leaseTime = 3600)
	{
		foreach ($this->queue as $key => $item) {
			if ($item->expire == 0) {
				$item->expire = time() + $leaseTime;
				$this->queue[$key] = $item;
				return $item;
			}
		}
		return false;
	}

	/**
	 * @param $item
	 */
	public function deleteItem($item)
	{
		unset($this->queue[$item->item_id]);
	}

	/**
	 * @param $item
	 * @return bool
	 */
	public function releaseItem($item)
	{
		if (isset($this->queue[$item->item_id]) && $this->queue[$item->item_id]->expire != 0) {
			$this->queue[$item->item_id]->expire = 0;
			return true;
		}
		return false;
	}

	/**
	 */
	public function createQueue()
	{
	}

	/**
	 * 删除队列
	 */
	public function deleteQueue()
	{
		$this->queue = array();
		$this->idSequence = 0;
	}
}